class BundlesController < ApplicationController
  # GET /bundles
  # GET /bundles.xml
  
  def index
    @bundles = Bundle.paginate :page => params[:page], :order => 'created_at DESC'

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @bundles }
    end
  end

  # GET /bundles/1
  # GET /bundles/1.xml
  def show
    @bundles = Bundle.find(params[:id], :include => [:bundle_variations])
    

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @bundles }
    end
  end

  # GET /bundles/new
  # GET /bundles/new.xml
  def new
    @bundles = Bundle.new
    publications_select
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @bundles }
    end
  end

  # GET /bundles/1/edit
  def edit
    @bundles = Bundle.find(params[:id])
    @statuses = Bundle.statuses
    publications_select
  end
  
  def publications_select
    @publications = Publication.find(:all)
    t = @bundles.publications.collect {|p| p.id }
    
    @publications_out = @publications.dup.delete_if {|p| t.include?(p.id) }
    @publications_in = @publications.dup.delete_if {|p| ! t.include?(p.id)}
  end
  
  # POST /bundles
  # POST /bundles.xml
  def create
    @bundles = Bundle.new(params[:bundle])
    @publications = Publication.find(:all)
    
    publications_select

    respond_to do |format|
      if @bundles.save
        flash[:notice] = 'Bundles was successfully created.'
        format.html { redirect_to(@bundles) }
        format.xml  { render :xml => @bundles, :status => :created, :location => @bundles }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @bundles.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /bundles/1
  # PUT /bundles/1.xml
  def update
    @bundles = Bundle.find(params[:id])
    @publications = Publication.find(:all)
    
    @statuses = Bundle.statuses
    
    publications_select

    respond_to do |format|
      if @bundles.update_attributes(params[:bundle])
        flash[:notice] = 'Bundles was successfully updated.'
        format.html { redirect_to(@bundles) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @bundles.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /bundles/1
  # DELETE /bundles/1.xml
  def destroy
    @bundles = Bundle.find(params[:id])
    @bundles.destroy

    respond_to do |format|
      format.html { redirect_to(bundles_url) }
      format.xml  { head :ok }
    end
  end
end
